import { isUndefined } from '@lagabu/tool';

type Pair = Array<number>;
type Pairs = Array<Pair>;

type Geometry = {
  coordinates: Array<Array<Pairs>> | Array<Pairs>;
  type: 'MultiPolygon' | 'Polygon';
};

type Feature = {
  type: 'Feature';
  geometry: Geometry;
  properties: { [props: string]: string };
};

type GeoJson = {
  type: 'FeatureCollection';
  features: Array<Feature>;
};

const excludeCountryCode = ['ATA'];

export function calculateX(x: number) {
  // return 180 + 2 * x;
  return 180 + x
  return x;
}

export function calculateY(y: number) {
  // return 180 + 2 * y - 30;
  return 180 + y
  return y;
}

function solvePair(pairs: Pairs) {
  let resultStr = '',
    prefix = 'M',
    x = '',
    y = '';
  for (let i = 0; i < pairs.length; i++) {
    let p = pairs[i];
    if (isUndefined(p[0]) || isUndefined(p[1])) {
      continue;
    }
    x = calculateX(p[0]).toFixed(2);
    y = calculateY(p[1]).toFixed(2);
    prefix = i === 0 ? 'M' : 'L';
    resultStr += `${prefix} ${x} ${y} `;
  }
  return resultStr;
}

function getPair(coor: Array<any>, type: 'MultiPolygon' | 'Polygon') {
  let resultStr = '';
  if (type === 'MultiPolygon') {
    for (let c of coor) {
      for (let pairs of c) {
        resultStr += solvePair(pairs);
      }
    }
  } else {
    for (let pairs of coor) {
      resultStr += solvePair(pairs);
    }
  }

  resultStr += 'Z ';
  return resultStr;
}

export function useConvertMap(json: GeoJson) {
  const resultArray = [];
  let key: string, coors: Array<any>;
  for (let f of json.features) {
    key = f.properties.A3;
    if (
      f.type === 'Feature' &&
      f.geometry &&
      !excludeCountryCode.includes(f.properties.A3)
    ) {
      coors = f.geometry.coordinates;
      resultArray.push({ name: key, path: getPair(coors, f.geometry.type) });
    }
  }
  return resultArray;
}
